package com.center.growcenterserver.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.center.growcenterserver.common.R;
import com.center.growcenterserver.model.domain.Student;
import com.center.growcenterserver.model.request.StudentRequest;
import com.center.growcenterserver.service.StudentService;
import com.center.growcenterserver.service.impl.StudentServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    /**
     * 管理界面调用：返回所有学生
     */
    @GetMapping("")
    public R allStudents(@RequestParam(defaultValue = "1") int curPage, @RequestParam(defaultValue = "100") int pageSize) {
        IPage<Student> page = new Page<>(curPage, pageSize);
        return studentService.allStudents(page);
    }

    /**
     * 学生登录
     */
    @PostMapping("/login/status")
    public R loginWithToken(@RequestBody StudentRequest loginRequest, HttpSession session) {
        return studentService.loginWithToken(loginRequest,session);
    }

    /**
     * 查询学生信息
     */
    @GetMapping("/info")
    public R selectStudentInfo() {
        return studentService.selectStudentInfo();
    }

    /**
     * 根据id删除单个学生
     */
    @GetMapping("/delete")
    public R deleteStudentById(String id) {
        return studentService.deleteStudentById(id);
    }

    /**
     * 根据ids删除多个学生
     */
    @DeleteMapping("/deleteIds")
    public R deleteStudentsByIds(String[] id) {
        return studentService.deleteStudentByIds(id);
    }

    /**
     * 添加新学生
     */
    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> addStudent(@RequestBody Student student) {
        Map<String, Object> response = new HashMap<>();
        try {
            int result = studentService.addStudent(student);
            if (result > 0) {
                response.put("success", true);
                response.put("message", "Student added successfully");
            } else {
                response.put("success", false);
                response.put("message", "Failed to add student");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "Error occurred: " + e.getMessage());
        }
        return new ResponseEntity<>(response, HttpStatus.OK);
    }

    /**
     * 更新学生头像
     */
    @PostMapping("/avatar/update")
    public ResponseEntity<Map<String, Object>> updateStudentAvatar(@RequestParam("id") String id, @RequestParam("file") MultipartFile file) {
        Map<String, Object> responseBody = new HashMap<>();
        try {
            Path uploadPath = Paths.get("src/img/studentPic/");
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            String filename = "student_" + id + "_" + file.getOriginalFilename();
            String safeUniqueFilename = java.net.URLEncoder.encode(filename, "UTF-8").replace("+", "%20");
            Path filePath = uploadPath.resolve(safeUniqueFilename);
            file.transferTo(filePath);
            String picUrl = "/img/studentPic/" + safeUniqueFilename;
            int updateCount = studentService.updateStudentImage(id, picUrl);

            if (updateCount > 0) {
                responseBody.put("success", true);
                responseBody.put("success", "File uploaded successfully");
                responseBody.put("url", picUrl);
                return ResponseEntity.ok(responseBody);
            } else {
                responseBody.put("success", false);
                responseBody.put("message", "Failed to update student's image in the database");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(responseBody);
            }
        } catch (IOException e) {
            responseBody.put("success", false);
            responseBody.put("message", "Failed to upload file due to an IO error");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(responseBody);
        }
    }

    /**
     * 更新学生信息
     */
    @PostMapping("/update")
    public R updateStudent(@RequestBody StudentRequest studentRequest) {
        log.info("Received update request: {}", studentRequest);

        try {
            return studentService.updateStudent(studentRequest);
        } catch (Exception e) {
            log.error("Error updating student", e);
            return R.error("Failed to update the student");
        }
    }

}
